<?php
namespace App;
use \Throwable;
use EasySwoole\Template\RenderInterface;
use think\Template as ThinkEngine;

/**
 * ThinkPHP Template Engine
 * Class Think
 * @package EasySwoole\Template\Test
 */
class Think implements RenderInterface
{
    private $engine;

    /**
     * Think constructor.
     * @param $viewsDir
     * @param string $cacheDir
     */
    function __construct($viewsDir = '/App/View/', $cacheDir = '/Temp/runtime/')
    {
        $config = [
            'view_path' => EASYSWOOLE_ROOT.$viewsDir,
            'cache_path' => EASYSWOOLE_ROOT.$cacheDir ,
            'view_suffix' => 'php',
        ];
        $this->engine = new ThinkEngine($config);
    }

    /**
     * 模板渲染
     * @param string $template
     * @param array $data
     * @param array $options
     * @return string|null
     */
    public function render(string $template, array $data = [], array $options = []): ?string
    {
        ob_start();
        $this->engine->assign($data);
        $this->engine->fetch($template);
        $content = ob_get_contents() ;
        return $content;
    }

    /**
     * 每次渲染完成都会执行清理
     * @param string|null $result
     * @param string $template
     * @param array $data
     * @param array $options
     */
    public function afterRender(?string $result, string $template, array $data = [], array $options = [])
    {

    }

    /**
     * 异常处理
     * @param Throwable $throwable
     * @return string
     * @throws Throwable
     */
    public function onException(\Throwable $throwable): string
    {
        $msg = "{$throwable->getMessage()} at file:{$throwable->getFile()} line:{$throwable->getLine()}";
        trigger_error($msg);
        return $msg;
    }
}